package cn.craftyun.serverlist.controller;

import cn.craftyun.serverlist.entity.Server;
import cn.craftyun.serverlist.entity.ServerState;
import cn.craftyun.serverlist.entity.User;
import cn.craftyun.serverlist.entity.UserRole;
import cn.craftyun.serverlist.param.ListServerParam;
import cn.craftyun.serverlist.service.IServerService;
import cn.craftyun.serverlist.service.IUserService;
import cn.craftyun.serverlist.vo.ResultEntity;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 用户端服务器管理
 */
@RestController
@RequestMapping("/api/server")
public class UserServerController {
    @Resource
    private IServerService serverService;
    @Resource
    private IUserService userService;

    /**
     * 列出服务器
     *
     * @param current 当前页
     * @return 服务器列表
     */
    @PostMapping("/list")
    public ResultEntity<IPage<Server>> list(@RequestParam Integer current, @RequestBody ListServerParam listServerParam) {
        User loginUser = userService.getLoginUser();
        // 普通用户限制ID
        if (loginUser != null
                && loginUser.getUserRole() == UserRole.ROLE_USER
                && !listServerParam.isShowAll()) {
            listServerParam.setUserId(loginUser.getId());
        }

        IPage<Server> page = serverService.selectPageByUser(new Page<>(current, 20), listServerParam);
        return ResultEntity.success("获取服务器列表成功", page);
    }

    /**
     * 获取单个服务器信息
     *
     * @param serverId 服务器ID
     * @return 服务器信息
     */
    @GetMapping("/get/{serverId}")
    public ResultEntity<Server> get(@PathVariable String serverId) {
        Server server = serverService.getById(serverId);
        if (server == null) {
            return ResultEntity.failed("服务器不存在");
        }

        return ResultEntity.success("获取服务器成功", server);
    }

    /**
     * 管理员更新服务器
     *
     * @param serverParam 服务器信息
     * @return 结果
     */
    public ResultEntity<Void> saveOrUpdateAdmin(Server serverParam) {
        if (serverParam.getId() == null) {
            return ResultEntity.failed("请使用普通账号增加");
        }
        serverService.updateById(serverParam);
        return ResultEntity.success("修改服务器成功");
    }

    /**
     * 更新或创建服务器
     *
     * @param serverParam 更新或创建的服务器
     * @return 更新或创建结果
     */
    @PostMapping("/saveOrUpdate")
    public ResultEntity<Void> saveOrUpdate(@RequestBody Server serverParam) {
        User loginUser = userService.getLoginUser();
        if (loginUser.getUserRole() >= UserRole.ROLE_ADMIN) {
            return saveOrUpdateAdmin(serverParam);
        }

        // 更新判断权限
        if (serverParam.getId() != null) {
            Server server = serverService.getById(serverParam.getId());
            if (server == null) {
                return ResultEntity.failed("服务器不存在");
            }
            if (!loginUser.getId().equals(server.getUserId())) {
                return ResultEntity.failed("用户无权限");
            }
        }
        // 设置用户ID
        serverParam.setUserId(loginUser.getId());
//        serverParam.setServerState(null);
        serverParam.setTitle(null);
        serverParam.setServerState(ServerState.STATE_WAIT_REVIEW);
        Assert.isTrue(serverService.saveOrUpdate(serverParam), "添加失败,请重试");
        return ResultEntity.success("添加或修改服务器成功");
    }

    /**
     * 删除服务器
     *
     * @param serverId 服务器ID
     * @return 删除结果
     */
    @PostMapping("/delete/{serverId}")
    public ResultEntity<Void> delete(@PathVariable String serverId) {
        User loginUser = userService.getLoginUser();

        Server server = serverService.getById(serverId);
        if (server == null) {
            return ResultEntity.failed("服务器不存在");
        }
        // 如果是普通用户判断权限
        if (loginUser.getUserRole() == UserRole.ROLE_USER && !server.getUserId().equals(loginUser.getId())) {
            return ResultEntity.failed("用户无权限");
        }
        Assert.isTrue(serverService.removeById(serverId), "删除服务器失败");
        return ResultEntity.success("删除服务器成功");
    }

    /**
     * 设置服务器状态
     *
     * @param serverId 服务器ID
     * @param state    状态
     * @return 更新结果
     */
    @PostMapping("/setState/{serverId}")
    public ResultEntity<Void> setState(@PathVariable String serverId, @RequestParam Integer state) {
        User loginUser = userService.getLoginUser();
        // 普通用户无权限
        if (loginUser.getUserRole() == UserRole.ROLE_USER) {
            return ResultEntity.failed("无权限");
        }
        Server server = serverService.getById(serverId);
        if (server == null) {
            return ResultEntity.failed("服务器不存在");
        }
        server.setServerState(state);

        serverService.updateById(server);
        return ResultEntity.success("设置成功");
    }

    @PostMapping("/setTitle/{serverId}")
    public ResultEntity<Void> setTitle(@PathVariable String serverId, @RequestParam String title) {
        User loginUser = userService.getLoginUser();
        // 普通用户无权限
        if (loginUser.getUserRole() == UserRole.ROLE_USER) {
            return ResultEntity.failed("无权限");
        }

        Server server = serverService.getById(serverId);
        if (server == null) {
            return ResultEntity.failed("服务器不存在");
        }
        server.setTitle(title);

        serverService.updateById(server);
        return ResultEntity.success("设置成功");
    }
}
